﻿namespace KeRui.URLRewriter
{
    using KeRui.URLRewriter.Config;
    using System;
    using System.Text.RegularExpressions;
    using System.Web;

    public class RewriterModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication app)
        {
            app.AuthorizeRequest += new EventHandler(this.URLRewriter);
        }

        protected void URLRewriter(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication) sender;
            string path = application.Request.Path;
            UrlsCollection urls = UrlsConfig.GetConfig().Urls;
            for (int i = 0; i < urls.Count; i++)
            {
                Regex regex = new Regex("^" + RewriterUtils.ResolveUrl(application.Context.Request.ApplicationPath, urls[i].VirtualUrl) + "$", RegexOptions.IgnoreCase);
                if (regex.IsMatch(path))
                {
                    string sendToUrl = RewriterUtils.ResolveUrl(application.Context.Request.ApplicationPath, regex.Replace(path, urls[i].DestinationUrl));
                    RewriterUtils.RewriteUrl(application.Context, sendToUrl);
                    break;
                }
            }
        }
    }
}

